"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const mobx_miniprogram_bindings_1 = require("mobx-miniprogram-bindings");
const index_1 = require("../../../store/index");
const dish_1 = require("../../../services/dish");
const order_1 = require("../../../services/order");
const toast_1 = require("../../../utils/toast");
const tabBar_1 = require("../../../utils/tabBar");
Page({
    data: {
        isChef: index_1.globalStore.isChef,
        loading: true,
        userProfile: index_1.globalStore.userProfile,
        categoryList: [],
        activeCategory: "all",
        menuList: [],
        filteredList: [],
        cartMap: {},
        cartCount: 0,
        cartItems: [],
        showCartPanel: false,
        submitLoading: false,
        inventoryCategories: [],
        inventoryActive: "all",
        inventoryMenu: [],
        inventoryFiltered: [],
        showEditPanel: false,
        editingId: "",
        editingName: "",
        editStock: 0,
        editFunValue: 0,
        saving: false,
        displayedMenu: [],
    },
    storeBindings: null,
    onLoad() {
        this.storeBindings = (0, mobx_miniprogram_bindings_1.createStoreBindings)(this, {
            store: index_1.globalStore,
            fields: ["categories", "menu", "cart", "userProfile", "isChef"],
            actions: ["setMenu", "setCart"],
        });
    },
    onUnload() {
        var _a, _b;
        (_b = (_a = this.storeBindings) === null || _a === void 0 ? void 0 : _a.destroyStoreBindings) === null || _b === void 0 ? void 0 : _b.call(_a);
    },
    onShow() {
        return __awaiter(this, void 0, void 0, function* () {
            yield index_1.globalStore.initAppData();
            const isChef = index_1.globalStore.isChef;
            this.setData({ isChef, userProfile: index_1.globalStore.userProfile });
            (0, tabBar_1.applyTabBar)(isChef ? "chef" : index_1.globalStore.isDiner ? "diner" : "guest");
            yield this.loadMenu();
            this.syncCategories();
            if (isChef) {
                this.setupInventory(index_1.globalStore.menu);
            }
            else {
                this.syncMenu(index_1.globalStore.menu);
                this.restoreCart();
            }
            this.updateDisplayedMenu();
        });
    },
    onPullDownRefresh() {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.loadMenu();
            wx.stopPullDownRefresh();
        });
    },
    loadMenu() {
        return __awaiter(this, void 0, void 0, function* () {
            this.setData({ loading: true });
            try {
                const res = yield (0, dish_1.fetchMenu)();
                index_1.globalStore.setMenu(res.menu);
                if (this.data.isChef) {
                    this.setupInventory(res.menu);
                }
                else {
                    this.syncMenu(res.menu);
                    this.rebuildCartState(this.data.cartMap, true);
                }
                this.updateDisplayedMenu();
            }
            catch (error) {
                console.error("加载菜单失败", error);
                wx.showToast({ title: "加载失败", icon: "none" });
            }
            finally {
                this.setData({ loading: false });
            }
        });
    },
    syncCategories() {
        const categories = index_1.globalStore.categories || [];
        const categoryList = [
            { key: "all", name: "全部", color: "#FFD7E2", icon: "🌈" },
            ...categories,
        ];
        this.setData({ categoryList });
    },
    syncMenu(menuList) {
        this.setData({ menuList }, () => {
            this.applyFilter(this.data.activeCategory || "all");
        });
    },
    applyFilter(categoryKey) {
        const source = this.data.menuList || [];
        const filtered = categoryKey === "all"
            ? source
            : source.filter((item) => item.categoryKey === categoryKey);
        this.setData({ activeCategory: categoryKey, filteredList: filtered }, () => {
            if (!this.data.isChef) {
                this.updateDisplayedMenu();
            }
        });
    },
    handleCategoryTap(event) {
        const { key } = event.currentTarget.dataset;
        if (this.data.isChef) {
            this.setData({ activeCategory: key });
            this.applyInventoryFilter(key);
            return;
        }
        this.applyFilter(key);
    },
    handleAddToCart(event) {
        const { id, enabled } = event.currentTarget.dataset;
        if (this.data.isChef) {
            this.handleToggleStatus(id, !(enabled !== null && enabled !== void 0 ? enabled : true));
            return;
        }
        this.updateCartQuantity(id, 1);
    },
    handleDecreaseCart(event) {
        if (this.data.isChef)
            return;
        const { id } = event.currentTarget.dataset;
        this.updateCartQuantity(id, -1);
    },
    updateCartQuantity(menuId, delta) {
        if (!menuId)
            return;
        const menuItem = this.data.menuList.find((item) => item._id === menuId);
        if (!menuItem) {
            (0, toast_1.toast)("菜品已下架");
            return;
        }
        if (!menuItem.isActive) {
            (0, toast_1.toast)("菜品未上架");
            return;
        }
        if (menuItem.stock <= 0) {
            (0, toast_1.toast)("今天售罄啦");
            return;
        }
        const cartMap = Object.assign({}, this.data.cartMap);
        const already = cartMap[menuId] ? 1 : 0;
        if (delta > 0) {
            if (already >= 1) {
                (0, toast_1.toast)("已加入餐单");
                return;
            }
            cartMap[menuId] = 1;
        }
        else if (already) {
            delete cartMap[menuId];
        }
        this.rebuildCartState(cartMap, true);
        if (delta > 0) {
            (0, toast_1.toast)("已加入餐单");
        }
    },
    rebuildCartState(cartMap, syncStore = false) {
        if (this.data.isChef)
            return;
        const menuList = this.data.menuList || [];
        const nextMap = {};
        const nextCart = [];
        const cartItems = [];
        Object.keys(cartMap).forEach((menuId) => {
            const menuItem = menuList.find((item) => item._id === menuId);
            if (!menuItem) {
                return;
            }
            const quantity = cartMap[menuId] ? 1 : 0;
            if (quantity <= 0 || menuItem.stock <= 0) {
                return;
            }
            nextMap[menuId] = 1;
            nextCart.push({
                menuId,
                name: menuItem.name,
                quantity,
                funValue: menuItem.funValue,
            });
            cartItems.push({
                menuId,
                name: menuItem.name,
                funValue: menuItem.funValue,
                coverUrl: menuItem.coverUrl,
            });
        });
        this.setData({
            cartMap: nextMap,
            cartCount: cartItems.length,
            cartItems,
            showCartPanel: cartItems.length ? this.data.showCartPanel : false,
        });
        if (syncStore) {
            index_1.globalStore.setCart(nextCart);
        }
    },
    restoreCart() {
        const cartMap = {};
        (index_1.globalStore.cart || []).forEach((item) => {
            cartMap[item.menuId] = item.quantity;
        });
        this.rebuildCartState(cartMap, true);
    },
    setupInventory(menu) {
        const categories = new Map();
        menu.forEach((item) => {
            if (!categories.has(item.categoryKey)) {
                categories.set(item.categoryKey, this.decorateCategory(item.categoryKey));
            }
        });
        const categoryList = [{ key: "all", name: "全部", icon: "🌈" }, ...Array.from(categories.values())];
        this.setData({
            inventoryCategories: categoryList,
            inventoryMenu: menu,
        });
        this.applyInventoryFilter(this.data.inventoryActive, menu);
    },
    decorateCategory(key) {
        const preset = {
            stirfry: { key, name: "热炒", icon: "🍲" },
            rice: { key, name: "主食", icon: "🍚" },
            fruit: { key, name: "鲜果", icon: "🍉" },
            snack: { key, name: "小食", icon: "🍡" },
            whole: { key, name: "粗粮", icon: "🥖" },
            dessert: { key, name: "甜品", icon: "🍰" },
            drink: { key, name: "饮品", icon: "🧃" },
        };
        return preset[key] || { key, name: key, icon: "🥗" };
    },
    applyInventoryFilter(activeKey, menuList) {
        const source = menuList !== null && menuList !== void 0 ? menuList : this.data.inventoryMenu;
        const filtered = activeKey === "all"
            ? source
            : source.filter((item) => item.categoryKey === activeKey);
        this.setData({
            inventoryActive: activeKey,
            inventoryFiltered: filtered,
        }, () => {
            if (this.data.isChef) {
                this.updateDisplayedMenu();
            }
        });
    },
    handleInventoryTab(event) {
        const { key } = event.currentTarget.dataset;
        this.applyInventoryFilter(key);
    },
    handleToggleStatus(menuId, isActive) {
        return __awaiter(this, void 0, void 0, function* () {
            try {
                const res = yield (0, dish_1.toggleDishStatus)(menuId, isActive);
                index_1.globalStore.updateMenuSnapshot(res.menu);
                (0, toast_1.toast)(isActive ? "已上架" : "已下架");
                this.setupInventory(index_1.globalStore.menu);
            }
            catch (error) {
                console.error("更新状态失败", error);
                wx.showToast({ title: "操作失败", icon: "none" });
            }
        });
    },
    handleOpenEdit(event) {
        if (!this.data.isChef)
            return;
        const { id } = event.currentTarget.dataset;
        const target = this.data.inventoryMenu.find((item) => item._id === id);
        if (!target)
            return;
        this.setData({
            showEditPanel: true,
            editingId: target._id,
            editingName: target.name,
            editStock: target.stock,
            editFunValue: target.funValue,
        });
    },
    handleCloseEdit() {
        this.setData({ showEditPanel: false, editingId: "" });
    },
    handleStep(event) {
        const { type, delta } = event.currentTarget.dataset;
        const step = delta === "dec" ? -1 : 1;
        if (type === "stock") {
            this.setData({ editStock: Math.max(0, this.data.editStock + step) });
        }
        else {
            this.setData({ editFunValue: Math.max(0, this.data.editFunValue + step) });
        }
    },
    handleStockInput(event) {
        const value = Math.max(0, Number(event.detail.value || 0));
        this.setData({ editStock: value });
    },
    handleFunInput(event) {
        const value = Math.max(0, Number(event.detail.value || 0));
        this.setData({ editFunValue: value });
    },
    handleSaveEdit() {
        return __awaiter(this, void 0, void 0, function* () {
            if (!this.data.editingId || this.data.saving)
                return;
            this.setData({ saving: true });
            try {
                const res = yield (0, dish_1.updateMenu)({
                    _id: this.data.editingId,
                    stock: this.data.editStock,
                    funValue: this.data.editFunValue,
                });
                index_1.globalStore.updateMenuSnapshot(res.menu);
                (0, toast_1.toast)("已更新库存");
                this.handleCloseEdit();
                this.setupInventory(index_1.globalStore.menu);
            }
            catch (error) {
                console.error("更新库存失败", error);
                wx.showToast({ title: "保存失败", icon: "none" });
            }
            finally {
                this.setData({ saving: false });
            }
        });
    },
    handleGoCart() {
        if (this.data.isChef) {
            wx.switchTab({ url: "/pages/user/cart/index" });
        }
    },
    handleToggleCartPanel() {
        if (this.data.isChef)
            return;
        if (!this.data.cartCount) {
            (0, toast_1.toast)("先挑几道菜吧");
            return;
        }
        this.setData({ showCartPanel: !this.data.showCartPanel });
    },
    handleRemoveCartItem(event) {
        if (this.data.isChef)
            return;
        const { id } = event.currentTarget.dataset;
        if (!id)
            return;
        const cartMap = Object.assign({}, this.data.cartMap);
        if (cartMap[id]) {
            delete cartMap[id];
            this.rebuildCartState(cartMap, true);
        }
    },
    handleSubmitCart() {
        return __awaiter(this, void 0, void 0, function* () {
            if (this.data.isChef || this.data.submitLoading)
                return;
            if (!this.data.cartItems.length) {
                (0, toast_1.toast)("请先选择菜品");
                return;
            }
            this.setData({ submitLoading: true });
            try {
                const payload = {
                    items: this.data.cartItems.map((item) => ({
                        menuId: item.menuId,
                        quantity: 1,
                    })),
                };
                const res = yield (0, order_1.submitOrder)(payload);
                index_1.globalStore.clearCart();
                this.rebuildCartState({}, true);
                this.setData({ showCartPanel: false });
                (0, toast_1.toast)("已提交订单");
                setTimeout(() => {
                    wx.switchTab({ url: "/pages/user/cart/index" });
                }, 300);
                if (res === null || res === void 0 ? void 0 : res.order) {
                    index_1.globalStore.updateOrderSnapshot(res.order);
                }
            }
            catch (error) {
                console.error("提交订单失败", error);
                (0, toast_1.toast)(error.message || "提交失败");
            }
            finally {
                this.setData({ submitLoading: false });
            }
        });
    },
    updateDisplayedMenu() {
        if (this.data.isChef) {
            this.setData({ displayedMenu: this.data.inventoryFiltered });
        }
        else {
            this.setData({ displayedMenu: this.data.filteredList });
        }
    },
});
